package o2o.web.actions.system.token;

import com.jinyou.utils.common.ValidateUtil;
import o2o.config.dao.DataDaoSql;
import o2o.config.dao.utils.DaoUtils;
import o2o.config.dao.utils.QueryCondition;
import o2o.config.memcached.MemcacheUtil;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.sys.UserTokenInfo;

import java.sql.SQLException;
import java.util.List;

public class MemTokenUtils {

    // 保存所有token
    public static void saveAllToken() {
        List<KeyValueBean> keyList = MemcacheUtil.getAllKeysBean();
        if (ValidateUtil.isAbsList(keyList)) {
            // 清空数据库现有的
            StringBuffer sbDel = new StringBuffer();
            sbDel.append("delete from ").append(PojoTables.D_USER_TOKE);
            try {
                DataDaoSql.getInstance().executeBySql(sbDel.toString());
            } catch (SQLException e) {
                e.printStackTrace();
            }

            StringBuffer sb = new StringBuffer();
            sb.append(" insert into ").append(PojoTables.D_USER_TOKE).append(" (username,token) values ('1','1')");
            for (int i = 0; i < keyList.size(); i++) {
                KeyValueBean info = keyList.get(i);
                if (null == info) {
                    continue;
                }
                // 保存到数据库
//                UserTokenInfo userTokenInfo = new UserTokenInfo();
//                userTokenInfo.setUsername(info.getKey());
//                userTokenInfo.setToken(info.getValue());
                sb.append(",('").append(info.getValue()).append("','").append(info.getKey()).append("')");
            }

            try {
                DataDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    // 恢复token
    public static void reBackToken() {
        QueryCondition query = QueryCondition.getInstance();
//        query.addCondition(Expression.getInstance().addChild("delFlag", 0));//所有未删除的
        String sql = DaoUtils.getSql(PojoTables.D_USER_TOKE, query);
        List<UserTokenInfo> list = null;
        try {
            list = (List<UserTokenInfo>) DataDaoSql.getInstance().list(UserTokenInfo.class, sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if (ValidateUtil.isAbsList(list)) {
            for (int i = 0; i < list.size(); i++) {
                UserTokenInfo info = list.get(i);
                if (null == info) {
                    continue;
                }

                if ("1".equalsIgnoreCase(info.getToken())) {
                    continue;
                }

                MemcacheUtil.getInstance().add(info.getToken(), info.getUsername());
            }
        }
    }
}
